﻿using AutoMapper;
using Sustainalytics.Entities.RiskRatings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Sustainalytics.ClientDW.Synchronization.SyncRiskRatingsData
{
    public class RiskRatingMaterialEsgIssueMapping
    {
        public static IEnumerable<RiskRatingMaterialEsgIssue> Map(
            Dictionary<Guid, CorporateDataLogic.RiskRatingCorporateData> corporateDetails,
            IList<SharedEntities.RiskRatingsResearch.ComprehensiveRiskRatingResearchProfile> riskRatingResearchProfiles)
        {
            return riskRatingResearchProfiles.SelectMany(researchProfile => MapIssues(researchProfile, corporateDetails));
        }

        private static IList<RiskRatingMaterialEsgIssue> MapIssues(
            SharedEntities.RiskRatingsResearch.ComprehensiveRiskRatingResearchProfile entity,
            Dictionary<Guid, CorporateDataLogic.RiskRatingCorporateData> corporateDetails
            )
        {
            var entities = entity.MaterialEsgIssues.Select(Mapper.Map<RiskRatingMaterialEsgIssue>).ToList();

            Parallel.ForEach(entities, mei =>
            {
                mei.CompanyId = entity.Id;
                mei.CapitalIqId = entity.CompanyId;
                mei.CompanyName = corporateDetails[entity.Id].CompanyName;
                mei.PeerGroup = corporateDetails[entity.Id].PeerGroup;
                mei.SubPeerGroup = corporateDetails[entity.Id].SubPeerGroup;
                mei.SubPeerGroupId = corporateDetails[entity.Id].SubPeerGroupId;
                mei.FinalBetaFactor = mei.FinalBetaFactor;
            });

            return entities;
        }
    }
}
